﻿using System;
using System.ComponentModel;
using System.Windows;
using MefBasic.Commans;
using Microsoft.Practices.Composite.Events;

namespace MefBasic
{
    public class MefApplication:Application
    {
        public static MefBasicBootstrapper Bootstrapper { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Bootstrapper = CreateBootstrapper();
            OnBeforeRunningBootstrapper();
            Bootstrapper.Run();
            OnAfterRunningBootstrapper();
            var mainWindow = CreateMainWindow();
            new MainWindowPresenter(mainWindow);
            mainWindow.Activated += HandleMainWindowActivated;
            mainWindow.Closing += HandleMainWindowClosing;
            OnBeforeShowingMainWindow();
            mainWindow.Show();
            OnAfterShowingMainWindow();
        }

        private void HandleMainWindowClosing(object sender, CancelEventArgs e)
        {
            if (Bootstrapper.Container.GetExportedValue<ShellPresenter>().Disabled)
            {
                e.Cancel = true;
                return;
            }
            DisableMainWindow(true);
            OnMainWindowClosing(e);
            if(e.Cancel)
                DisableMainWindow(false);
        }

        private void DisableMainWindow(bool disabled)
        {
            Bootstrapper.Container.GetExportedValue<IEventAggregator>().GetEvent<BaseEvent<ShellDisabledChangedEventArgs>>().Publish(new ShellDisabledChangedEventArgs() { Sender = this, Disabled = disabled });
        }

        protected virtual void OnMainWindowClosing(CancelEventArgs e)
        {
            
        }

        protected virtual IMainWindow CreateMainWindow()
        {
            return new MainWindow();
        }

        protected virtual void OnAfterShowingMainWindow()
        {
            
        }

        protected virtual void OnBeforeShowingMainWindow()
        {
            
        }

        private static void HandleMainWindowActivated(object sender, EventArgs e)
        {
            var mainWindow = ((Window)sender);
            Current.MainWindow = mainWindow;
            mainWindow.Activated -= HandleMainWindowActivated;
            Bootstrapper.Container.GetExportedValue<ShellPresenter>().Initialize(mainWindow);
        }

        protected virtual void OnBeforeRunningBootstrapper()
        {
            
        }
        protected virtual void OnAfterRunningBootstrapper()
        {

        }

        protected virtual void DoInitialize()
        {
            
        }

        protected virtual MefBasicBootstrapper CreateBootstrapper()
        {
            return new MefBasicBootstrapper();
        }
    }
}
